package com.os.opencv.java.chapter7;

import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Size;
import org.opencv.highgui.HighGui;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

public class Thinning {

    public static void main(String[] args) {
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
        //读取图像并在屏幕上显示
        Mat image = Imgcodecs.imread("/Users/matt/Pictures/dog.jpg");
        Mat gray = new Mat();
        Imgproc.cvtColor(image, gray, Imgproc.COLOR_BGR2GRAY);
        //将灰度图反相并在屏幕上显示
        Core.bitwise_not(gray, gray);
        HighGui.imshow("gray", gray);
        HighGui.waitKey(0);

        //进行高斯滤波和二值化处理
        Imgproc.GaussianBlur(gray, gray, new Size(5,5), 2);
        Imgproc.threshold(gray, gray, 20, 255, Imgproc.THRESH_BINARY);

        HighGui.imshow("binary", gray);
        HighGui.waitKey(0);

        //计算街区距离
        Mat thin = new Mat(gray.size(), CvType.CV_32FC1);
        Imgproc.distanceTransform(gray, thin, Imgproc.DIST_L1, 3);

        //获取最大的街区距离
        float max = 0;
        for(int i=0; i<thin.rows(); i++){
            for(int j=0; j<thin.cols(); j++){
                float[] f = new float[3];
                thin.get(i, j, f);  //获取像素值
                if(f[0] > max){
                    max = f[0];
                }
            }
        }

        //定义用于显示结果的矩阵，背景为全黑
        Mat show = Mat.zeros(gray.size(), CvType.CV_8UC1);

        //将距离符合一定条件的像素设置为白色
        for(int i=0; i<thin.rows(); i++){
            for(int j=0; j<thin.cols(); j++){
                float[] f = new float[3];
                thin.get(i,j,f);
                if(f[0] > max/3){
                    show.put(i,j,255);
                }
            }
        }

        //在屏幕上显示最后的结果
        HighGui.imshow("thin", show);
        HighGui.waitKey(0);

        System.exit(0);
    }
}
